<template>
    <div class="score">
      <el-button type="primary" round @click="dialogFormVisible = true">增加成绩</el-button>
      <el-dialog :title="isEdit ? '更新成绩':'增加成绩'" :visible.sync="dialogFormVisible" :before-close="handleClose" >
        <el-form :model="form" status-icon :rules="rules" ref="form" label-width="100px" >
            <el-form-item label="学号"  required prop="sid">
              <el-input v-model.number="form.sid" style="width:200px" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="姓名"  required prop="name">
              <el-input v-model="form.name" autocomplete="off" style="width:200px" oninput="if(value.length > 11)value = value.slice(0, 11)"></el-input>
            </el-form-item>
            <el-form-item label="德育分数"  required prop="virtue">
              <el-input v-model.number="form.virtue" autocomplete="off" style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="智育分数"  required prop="intelligence">
              <el-input v-model.number="form.intelligence" autocomplete="off" style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="体育分数"  required prop="sports">
              <el-input v-model.number="form.sports" autocomplete="off" style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="美育分数"  required prop="art">
              <el-input v-model.number="form.art" autocomplete="off" style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="劳育分数"  required prop="labor">
              <el-input v-model.number="form.labor" autocomplete="off" style="width:200px"></el-input>
            </el-form-item>
            <!-- <el-form-item label="评语"  prop="remark">
              <el-input type="textarea" v-model="form.remark" autocomplete="off"></el-input>
            </el-form-item> -->
            <el-form-item label="老师"  required prop="tid">
              <el-select v-model="form.tid">
                <el-option v-for="item in teachers" :value="item.teacherID" :label="item.username"/>
              </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancle">取 消</el-button>
          <el-button type="primary" @click="handleForm">确 定</el-button>
        </div>
    </el-dialog>
      <el-radio-group v-model.number="system" class="system">
        <el-radio-button label="1">百分制</el-radio-button>
        <el-radio-button label="2">等级制</el-radio-button>
      </el-radio-group>

      <div v-show="dialog_visible">

      <el-select v-model="tid1">
              <el-option v-for="item in teachers" :value="item.teacherID" :label="item.username" />
      </el-select>
      <el-button class="searchbtn" type="primary" icon="el-icon-search" @click="test">选择</el-button>

  </div>
      <el-table
    :data="list"
    style="width: 100%"
    height="620"
    border="1"
    stripe="1"
    @sort-change="sortChange"
    >

    <el-table-column
      prop="sid"
      label="学号"
      width="120">
    </el-table-column>
    <el-table-column
      prop="name"
      label="姓名"
      width="120">
    </el-table-column>
    <el-table-column
      prop="virtue"
      label="德育成绩"
      width="110"
      sortable="custom">
    </el-table-column>
    <el-table-column
      prop="intelligence"
      label="智育成绩"
      width="110"
      sortable="custom">
    </el-table-column>
    <el-table-column
      prop="sports"
      label="体育成绩"
      width="110"
      sortable="custom">
    </el-table-column>
    <el-table-column
      prop="art"
      label="美育成绩"
      width="110"
      sortable="custom">
    </el-table-column>
    <el-table-column
      prop="labor"
      label="劳育成绩"
      width="110"
      sortable="custom">
    </el-table-column>
    <!-- <el-table-column
      prop="remark"
      label="评语"
      width="180"
      show-overflow-tooltip>
    </el-table-column> -->
    <el-table-column
      prop="teacher.username"
      label="教师名称"
      width="120"

      >
      <!-- :filters="teachersFilter"
      :filter-method="filterHandler" -->
    </el-table-column>
    <el-table-column
      prop="totalScore"
      label="总评成绩"
      width="120"
      sortable="custom">
    </el-table-column>
    <el-table-column

      label="操作"
      width="375">
      <template slot-scope="scope">
        <el-button
        type="primary" icon="el-icon-edit"
          @click.native.prevent="handleUpdate(scope.row)"
          >
          编辑
        </el-button>
        <el-button
        type="danger" slot="reference" icon="el-icon-delete"
          @click.native.prevent="$event => handleDelete(scope.row.id)"
          >
          删除
        </el-button>
        <el-button
        type="primary"
          size="small"
          @click.native.prevent="$event => handleGenerateScore(scope.row)"
          >
          生成总评成绩
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :hide-on-single-page="true"
      background
      class="pagination"
      >
    </el-pagination>
    </div>
</template>

<script>
import request from "@/utils/re_request"
import { Message } from 'element-ui';
export default {
    name:'show',
    data() {
        // 验证ID是否已经存在
        var validateSid = (rule, value, callback) => {
          if(!Number.isInteger(value)){
            callback(new Error('请正确输入学号！'))
          }else if(value.toString().length !== 10 ){
            callback(new Error('学号应为10位数字!'))
          }else {
            this.studentIdIsExist(value).then(
              isExist => {
                if(isExist) {
                  callback(new Error('当前学号已存在！'))
                }else {
                  callback()
                }
              }
            )
          }
        }
        var validateScore = (rule, value, callback) => {
          if(!Number.isInteger(value)){
            callback(new Error('请正确输入分数！'))
          }else if(value < 0 || value > 100){
            callback(new Error('成绩输入范围为 0~100 '))
          }else{
            callback()
          }
        }
        return {
            data:[],//原始数据
            list: [],//显示数据
            system:1, //
            currentPage: 1,//当前页
            pageSize: 10,//每页显示记录数
            total: 0,//总记录数
            dialogFormVisible:false, // 表单是否显示
            dialog_visible: false,
            isadmin:0,
            keyborde:0,
            defaultTid: 1,
            tid1:1,

            teachers:[], // 教师数据,
            teachersFilter:[],// 教师过滤数据
            form:{ // 表单
              sid:'',
              name:'',
              virtue:'',
              intelligence:'',
              sports:'',
              art:'',
              labor:'',
              remark:'',
              tid:'',
            },
            // 表单校验规则
            rules:
            {
              sid:[{required:true,  validator: validateSid, trigger:'blur'}],
              name:[{required:true, message: '请输入姓名', trigger:'blur'}],
              virtue:[{required:true,  validator: validateScore, trigger: 'blur'}],
              intelligence:[{required:true,  validator: validateScore, trigger: 'blur'}],
              sports:[{required:true,  validator: validateScore, trigger: 'blur'}],
              art:[{required:true,  validator: validateScore, trigger: 'blur'}],
              labor:[{required:true,  validator: validateScore, trigger: 'blur'}],
            },
            // 是否是更新操作
            isEdit:false,
            // 操作的id
            operationId:0,
            // 总评分
            totalScore:'',

        }
    },
    watch:{
      // 监听system是否变化
      system: {
        handler(val) {
          if(val === 1) {
            this.list = this.data
          } else {
            this.list = this.generateHierarchy(this.data)
          }
        },
      },
      isadmin:{
        handler(val){
          if(val === '100000'){
            this.dialog_visible = true
            this.getData()
          }else{
            this.dialog_visible = false
            this.tid1 = localStorage.teacherId
            this.getData()
          }
        }
      }
    },
    methods: {
        getUser(){
          var temp = localStorage.teacherId;
          this.isadmin = temp;
        },
        test(){
          this.list= [],
          this.$nextTick(()=>{
                      this.keyborde++;
                    })
          this.getData()
        },
        // 获取学生表现数据
        getData() {
            request.post(`/performance/all?tid=${this.tid1}`).then(
                response => {
                    if(response.code === 600) {
                        this.data = response.data
                        // this.data = response.data.slice(0, this.pageSize)
                        if(this.system === 1) {
                          this.list = response.data.slice(0, this.pageSize)
                        } else {
                          this.list = response.data.slice(0, this.pageSize)
                          this.list = this.generateHierarchy(this.list)
                        }
                        this.total = response.count
                        // Message.success(response.msg)
                    }
                }
            )
        },
        // 当前页变化
        handleCurrentChange(currentPage) {
          this.currentPage = currentPage
          this.list = this.data.slice(this.pageSize * (currentPage - 1), this.pageSize * currentPage)
        },
        // 页面大小更新
        handleSizeChange(pageSize) {
          this.currentPage = 1
          this.pageSize = pageSize
          this.list = this.data.slice(0, pageSize)
        },
        // 生成等级制数据
        generateHierarchy(data) {
          const str = JSON.stringify(data);
          const newData = JSON.parse(str);
          return newData.map((item) => {
            item.virtue = this.scoreToGrade(item.virtue)
            item.intelligence = this.scoreToGrade(item.intelligence)
            item.sports = this.scoreToGrade(item.sports)
            item.art = this.scoreToGrade(item.art)
            item.labor = this.scoreToGrade(item.labor)
            console.log(item.totalScore)
            item.totalScore = item.totalScore !== undefined ? this.scoreToGrade(item.totalScore) : ''

            return item
          })
        },
        // 成绩与等级转化
        scoreToGrade(score) {
          var grade = ""
          if(score >= 90) {
            grade = "A"
          } else if(score >= 80) {
            grade = "B"
          } else if(score >= 70){
            grade = "C"
          } else if(score >= 60){
            grade = "D"
          } else {
            grade = "E"
          }
          return grade
        },
        // 验证学生ID是否存在
        async studentIdIsExist(sid) {
          const isExist = await request.get(`/performance/exist?sid=${sid}`).then(
             response => {
              if(response.code === 600) {
                return response.data ? true : false
              }
            }
          )
          return isExist
        },
        // 获取老师数据
        getTeacherData() {
          request.get('/teacher/list').then(
            response => {
              if(response.code === 600) {
                this.teachers = response.data
                // 生成根据老师数据筛选数据
                var teachersFilter = []
                for(var item of response.data) {
                  var teacherFileter = {}
                  teacherFileter.text = item.username
                  teacherFileter.value = item.teacherID
                  teachersFilter.push(teacherFileter)
                }
                this.teachersFilter = teachersFilter
            }
          }
          )
        },
        // 对学生数据根据教师ID筛选
        filterHandler(value, row, column) {
          return row.teacher.teacherID === value;
        },
        // 处理增加或者编辑逻辑
        handleForm() {
          // 关闭对话框
          this.dialogFormVisible = false
          // 根据isEdit处理逻辑
          // 后端处理
          if(this.isEdit) {
            request.put('/performance/update', {
              id: this.operationId,
              ...this.form,
              totalScore: this.totalScore ? this.totalScore : ''
            }).then(
              response => {
                if(response.code === 600) {
                  // 前端更新
                  this.getData()
                  Message.success(response.msg)
                }
              }
            )
          } else {
            request.post('/performance/add', {
              ...this.form
            }).then(
              response => {
                if(response.code === 600) {
                  // 前端更新
                  this.getData()
                  Message.success(response.msg)
                }
              }
            )
          }
          // 重置form和isEdit
          // 清空表单中的值
          this.$refs["form"].resetFields()
          this.isEdit = false
        },
        // 处理学生表现数据更新
        handleUpdate(item) {
          // 将isEdit设置为true方便对话框确定时的逻辑处理
          this.isEdit = true
          // 记录totalScore，方便更新学生成绩数据时将总评分也进行更新
          // 假如为等级制
          if(this.system === 2) {
            this.totalScore = this.data.filter((i) => item.id === i.id)[0].totalScore
          } else {
            this.totalScore = item.totalScore
          }
          // 开启对话框
          this.dialogFormVisible = true

          // 填充数据
          this.$nextTick(()=>{
		        //在这里进行对form表单的赋值
            if(this.system === 2) {
              // 分数等级制
              item = this.data.filter((i) => item.id === i.id)[0]
            }
            for(let key in item) {
              if(this.form.hasOwnProperty(key)) {
                this.form[key] = item[key];
              }
            }
            this.form.tid = item.teacher.teacherID
            this.operationId = item.id
	        })

        },
        // 处理从下方的取消 确定关闭对话框
        handleCancle() {
          // 关闭对话框
          this.dialogFormVisible = false

          // 清空表单中的值并重置isEdit和totalScore
          this.$refs["form"].resetFields()
          this.isEdit = false
          this.totalScore = ''
        },
        // 处理从右上角的的×关闭对话框
        handleClose(done){
          this.$confirm('确认关闭？')
          .then(_ => {
            this.handleCancle()
            done();
          })
          .catch(_ => {});
        },
        // 处理删除数据的逻辑
        handleDelete(id) {
          this.$confirm('确认删除吗？')
          .then(_ => {
            request.delete('/performance/delete', {
              data:{
                'id': id
              }
            }).then(
              response => {
                if(response.code === 600) {
                  this.getData()
                  Message.success(response.msg)
                }
              }
            )
          })
          .catch(_ => {});
        },
        // 生成总评成绩
        handleGenerateScore(item) {
          if(this.system === 2) {
            // this.data.filter((i) => item.id === i.id)过滤出来一个列表，需要选第一个
            item = (this.data.filter((i) => item.id === i.id))[0]
          }
          if(item.totalScore != null){
            Message.error("成绩已存在！")
          }else{
          request.put('/performance/generate', {
            id: item.id,
            virtue:item.virtue,
            intelligence: item.intelligence,
            sports:item.sports,
            art:item.art,
            labor:item.labor,
            tid: item.teacher.teacherID,
          }).then(
            response => {
              if(response.code === 600) {
                this.getData()
                Message.success("生成成功！")
              }
            }
          )
          }
        },

        sortChange(column) {
          this.data = this.data.sort(
          this.SortFun(column.prop, column.order === "ascending")
          );
          this.list = this.data.slice(0, this.pageSize);
          this.currentPage = 1;
        },

         // 排序方法
        SortFun(attr, rev) {
          this.currentPage = 1;
          //第一个参数传入info里的prop表示排的是哪一列，第二个参数是升还是降排序
          if (rev == undefined) {
            rev = 1;
          } else {
            rev = rev ? 1 : -1;
            //rev = rev>0 ? 1 : -1;
          }
          return function (a, b) {
            a = a[attr];
            b = b[attr];
            if (a != null) {
              if (typeof a == "number") {
                if (a < b) {
                  return rev * -1;
                }
                if (a > b) {
                  return rev * 1;
                }
                return 0;
              }
            }
          };
        },


    },
    mounted(){
        this.getUser()
        // this.getData()
        this.getTeacherData()
    },
}
</script>

<style>
  .score{
    margin: 30px 50px 0 50px;
  }

  .system{
    margin-left: 20px;
  }

  .pagination {
    margin-left: 30%;
    font-size: 14px;
  }
</style>
